home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / TEXTINDEX.PY < prev    next >
Encoding:
Python Source  |  2000-03-14  |  15.0 KB  |  456 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64.  
  65. """Text Index
  66.  
  67. Notes on a new text index design
  68.  
  69.   The current inverted index algoirthm works well enough for our needs.
  70.   Speed of the algorithm does not seem to be a problem, however, data
  71.   management *is* a significant problem.  In particular:
  72.  
  73.     - Process size grows unacceptably *during mass indexing*.
  74.  
  75.     - Data load and store seems to take too long.  For example,
  76.       clearing an inverted index and committing takes a significant
  77.       amount of time.
  78.  
  79.     - The current trie data structure contributes significantly to the
  80.       number of objects in the system.
  81.  
  82.     - Removal/update of documents is especially problematic.  We have
  83.       to either:
  84.  
  85.       - Unindex old version of an object before updating it.  This is
  86.         a real hassle for apps like sws.
  87.  
  88.       - Tool through entire index looking for object references.  This
  89.         is *totally* impractical.
  90.  
  91.   Some observations of competition:
  92.  
  93.     - Xerox system can index "5-million word document in 256k".  What
  94.       does this mean?
  95.  
  96.         - Does the system save word positions as we do?
  97.  
  98.         - What is the index indexing?
  99.  
  100.         - What was the vocabulary of the system?
  101.  
  102.       Let\'s see.  Assume a 10,000 word vocabulary.  Then we use
  103.       25-bytes per entry.  Hm.....
  104.  
  105.     - Verity has some sense of indexing in phases and packing index.
  106.       Verity keeps the index in multiple chunks and a search may
  107.       operate on multiple chunks.  This means that we can add data
  108.       without updating large records.
  109.  
  110.       This may be especially handy for mass updates, like we do in
  111.       cv3.  In a sense we do this in cv3 and sws.  We index a large
  112.       batch of documents to a temporary index and then merge changes
  113.       in.
  114.  
  115.       If "temporary" index was integral to system, then maybe merger
  116.       could be done as a background task....
  117.  
  118.   Tree issues
  119.  
  120.     Tree structures benefit small updates, because an update to an
  121.     entry does not cause update of entire tree, however, each node in
  122.     tree introduces overhead.
  123.  
  124.     Trie structure currently introduces an excessive number of nodes.
  125.     Typically, a node per two or three words.  Trie has potential to 
  126.     reduce storage because key storage is shared between words.
  127.  
  128.     Maybe an alternative to a Trie is some sort of nested BTree.  Or
  129.     maybe a Trie with some kind of binary-search-based indexing.
  130.  
  131.     Suppose that:
  132.  
  133.       - database objects were at leaves of tree
  134.       - vocabulary was finite
  135.       - we don\'t remove a leaf when it becomes empty
  136.  
  137.     Then:
  138.  
  139.       - After some point, tree objects no longer change
  140.     
  141.     If this is case, then it doesn\'t make sense to optimize tree for
  142.     change. 
  143.  
  144.   Additional notes
  145.  
  146.     Stemming reduces the number of words substantially.
  147.  
  148.   Proposal -- new TextIndex
  149.  
  150.     TextIndex -- word -> textSearchResult
  151.  
  152.       Implemented with:
  153.  
  154.         InvertedIndex -- word -> idSet
  155.  
  156.         ResultIndex -- id -> docData
  157.  
  158.         where:
  159.  
  160.           word -- is a token, typically a word, but could be a name or a
  161.                   number
  162.  
  163.           textSearchResult -- id -> (score, positions)
  164.  
  165.           id -- integer, say 4-byte.
  166.           
  167.           positions -- sequence of integers.
  168.  
  169.           score -- numeric measure of relevence, f(numberOfWords, positions)
  170.  
  171.           numberOfWords -- number of words in source document.
  172.  
  173.           idSet -- set of ids
  174.  
  175.           docData -- numberOfWords, word->positions
  176.  
  177.        Note that ids and positions are ints.  We will build C
  178.        extensions for efficiently storing and pickling structures
  179.        with lots of ints.  This should significantly improve space
  180.        overhead and storage/retrieveal times, as well as storeage
  181.        space.
  182.  
  183. """
  184. __version__='$Revision: 1.25 $'[11:-2]
  185.  
  186. from Globals import Persistent
  187. import BTree, IIBTree
  188. BTree=BTree.BTree
  189. IIBTree=IIBTree.Bucket
  190. from intSet import intSet
  191. import operator
  192. from Splitter import Splitter
  193. from string import strip
  194. import string, ts_regex, regex
  195.  
  196. from Lexicon import Lexicon, query, stop_word_dict
  197. from ResultList import ResultList
  198.  
  199. class TextIndex(Persistent):
  200.  
  201.     def __init__(self, data=None, schema=None, id=None,
  202.                  ignore_ex=None, call_methods=None):
  203.         """Create an index
  204.  
  205.         The arguments are:
  206.  
  207.           'data' -- a mapping from integer object ids to objects or
  208.           records,
  209.  
  210.           'schema' -- a mapping from item name to index into data
  211.           records.  If 'data' is a mapping to objects, then schema
  212.           should ne 'None'.
  213.  
  214.           'id' -- the name of the item attribute to index.  This is
  215.           either an attribute name or a record key.
  216.  
  217.           'ignore_ex' -- Tells the indexer to ignore exceptions that
  218.           are rasied when indexing an object.
  219.  
  220.           'call_methods' -- Tells the indexer to call methods instead
  221.           of getattr or getitem to get an attribute.
  222.  
  223.         """
  224.         ######################################################################
  225.         # For b/w compatability, have to allow __init__ calls with zero args
  226.         if not data==schema==id==ignore_ex==call_methods==None:
  227.             self._data=data
  228.             self._schema=schema
  229.             self.id=id
  230.             self.ignore_ex=ignore_ex
  231.             self.call_methods=call_methods
  232.             self._index=BTree()
  233.             self._syn=stop_word_dict
  234.             self._reindex()
  235.         else:
  236.             pass
  237.  
  238.     # for backwards compatability
  239.     _init = __init__
  240.  
  241.  
  242.     def clear(self):
  243.         self._index = BTree()
  244.  
  245.  
  246.     def positions(self, docid, words):
  247.         """Return the positions in the document for the given document
  248.         id of the word, word."""
  249.         id = self.id
  250.  
  251.         if self._schema is None:
  252.             f = getattr
  253.         else:
  254.             f = operator.__getitem__
  255.             id = self._schema[id]
  256.  
  257.  
  258.         row = self._data[docid]
  259.  
  260.         if self.call_methods:
  261.             doc = str(f(row, id)())
  262.         else:
  263.             doc = str(f(row, id))
  264.  
  265.         r = []
  266.         for word in words:
  267.             r = r+Splitter(doc, self._syn).indexes(word)
  268.         return r
  269.  
  270.  
  271.     def index_item(self, i, obj=None, un=0):
  272.         """Recompute index data for data with ids >= start.
  273.         if 'obj' is passed in, it is indexed instead of _data[i]"""
  274.  
  275.         id = self.id
  276.         if (self._schema is None) or (obj is not None):
  277.             f = getattr
  278.         else:
  279.             f = operator.__getitem__
  280.             id = self._schema[id]
  281.  
  282.         if obj is None:
  283.             obj = self._data[i]
  284.  
  285.         try:
  286.             if self.call_methods:
  287.                 k = str(f(obj, id)())
  288.             else:
  289.                 k = str(f(obj, id))
  290.  
  291.             self._index_document(k, i ,un)
  292.         except:
  293.             pass
  294.  
  295.  
  296.     def unindex_item(self, i, obj=None): 
  297.         return self.index_item(i, obj, 1)
  298.  
  299.  
  300.     def _reindex(self, start=0):
  301.         """Recompute index data for data with ids >= start."""
  302.         for i in self._data.keys(start): self.index_item(i)
  303.  
  304.  
  305.     def _index_document(self, document_text, id, un=0,
  306.                         tupleType=type(()),
  307.                         dictType=type({}),
  308.                         ):
  309.         src = Splitter(document_text, self._syn)  
  310.  
  311.         d = {}
  312.         old = d.has_key
  313.         last = None
  314.         
  315.         for s in src:
  316.             if s[0] == '\"': last=self.subindex(s[1:-1], d, old, last)
  317.             else:
  318.                 if old(s):
  319.                     if s != last: d[s] = d[s]+1
  320.                 else: d[s] = 1
  321.  
  322.         index = self._index
  323.         get = index.get
  324.         if un:
  325.             for word,score in d.items():
  326.                 r = get(word)
  327.                 if r is not None:
  328.                     if type(r) is tupleType: del index[word]
  329.                     else:
  330.                         if r.has_key(id): del r[id]
  331.                         if type(r) is dictType:
  332.                             if len(r) < 2:
  333.                                 if r:
  334.                                     for k, v in r.items(): index[word] = k,v
  335.                                 else: del index[word]
  336.                             else: index[word] = r
  337.         else:
  338.             for word,score in d.items():
  339.                 r = get(word)
  340.                 if r is not None:
  341.                     r = index[word]
  342.                     if type(r) is tupleType:
  343.                         r = {r[0]:r[1]}
  344.                         r[id] = score
  345.                         index[word] = r
  346.                     elif type(r) is dictType:
  347.                         if len(r) > 4:
  348.                             b = IIBTree()
  349.                             for k, v in r.items(): b[k] = v
  350.                             r = b
  351.                         r[id] = score
  352.                         index[word] = r
  353.                     else: r[id] = score
  354.                 else: index[word] = id, score
  355.  
  356.  
  357.     def _subindex(self, isrc, d, old, last):
  358.  
  359.         src = Splitter(isrc, self._syn)  
  360.  
  361.         for s in src:
  362.             if s[0] == '\"': last=self.subindex(s[1:-1],d,old,last)
  363.             else:
  364.                 if old(s):
  365.                     if s != last: d[s] = d[s]+1
  366.                 else: d[s] = 1
  367.  
  368.         return last
  369.  
  370.  
  371.     def __getitem__(self, word):
  372.         """Return an InvertedIndex-style result "list"
  373.         """
  374.         src = tuple(Splitter(word, self._syn))
  375.         if not src: return ResultList({}, (word,), self)
  376.         if len(src) == 1:
  377.             src=src[0]
  378.             if src[:1]=='"' and src[-1:]=='"': return self[src]
  379.             r = self._index.get(word,None)
  380.             if r is None: r = {}
  381.             return ResultList(r, (word,), self)
  382.             
  383.         r = None
  384.         for word in src:
  385.             rr = self[word]
  386.             if r is None: r = rr
  387.             else: r = r.near(rr)
  388.  
  389.         return r
  390.  
  391.  
  392.     def _apply_index(self, request, cid='', ListType=[]): 
  393.         """ Apply the index to query parameters given in the argument,
  394.         request
  395.  
  396.         The argument should be a mapping object.
  397.  
  398.         If the request does not contain the needed parameters, then
  399.         None is returned.
  400.  
  401.         Otherwise two objects are returned.  The first object is a
  402.         ResultSet containing the record numbers of the matching
  403.         records.  The second object is a tuple containing the names of
  404.         all data fields used.  
  405.         """
  406.  
  407.         id = self.id
  408.  
  409.         cidid = "%s/%s" % (cid, id)
  410.         has_key = request.has_key
  411.         if has_key(cidid): keys = request[cidid]
  412.         elif has_key(id): keys =request[id]
  413.         else: return None
  414.  
  415.         if type(keys) is type(''):
  416.             if not keys or not strip(keys): return None
  417.             keys = [keys]
  418.         r = None
  419.         for key in keys:
  420.             key = strip(key)
  421.             if not key: continue
  422.             rr = intSet()
  423.             try:
  424.                 for i,score in query(key,self).items():
  425.                     if score: rr.insert(i)
  426.             except KeyError: pass
  427.             if r is None: r = rr
  428.             else:
  429.                 # Note that we *and*/*narrow* multiple search terms.
  430.                 r = r.intersection(rr) 
  431.  
  432.         if r is not None: return r, (id,)
  433.         return intSet(), (id,)
  434.  
  435.